package com.cabrida.livestar.main.me;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.main.MainActivity;
import com.cabrida.livestar.util.Bimp;
import com.cabrida.livestar.util.FileUtils;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.ImageUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.MyUtils;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.SharedUtils;
import com.cabrida.livestar.util.StringUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 修改头像
 * 
 * @author why
 */
public class PersonalChangeHeaderActivity extends BaseActivity {
	public static final String TAG = PersonalChangeHeaderActivity.class
			.getSimpleName();
	private ImageView iv_back;
	private TextView tv_title;
	private TextView tv_right;
	private ImageView iv_header;
	private String str_path;
	private String str_file;

	private Dialog dialogHead;

	private String protraitPath;
	private Bitmap protraitBitmap;
	private File protraitFile;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/LiveStar/Portrait/";
	private Uri origUri;
	private Uri cropUri;
	private final static int CROP = 600;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_personal_changeheader);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_right = (TextView) findViewById(R.id.tv_right);
		iv_header = (ImageView) findViewById(R.id.iv_header);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		tv_right.setOnClickListener(this);
		iv_header.setOnClickListener(this);
		tv_title.setText(getResources().getString(
				R.string.fans_change_information_pensonal));
		tv_right.setText(getResources().getString(R.string.finish));
		MyUtils.loadImg(Global.headPic, iv_header);
	}

	/**
	 * 上传新照片
	 */
	private void uploadNewPhoto() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		try {
			params.put("img", protraitFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_IMGUPLOAD_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "uploadNewPhoto", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							str_path = JsonUtils.getString(data,"path", "");
							str_file = JsonUtils.getString(data,"file", "");
							protraitBitmap = Bimp.getSmallBitmap(protraitPath);
							iv_header.setImageBitmap(protraitBitmap);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	private void getHeaderData() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("path", str_path);
		params.put("file", str_file);

		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_PERSONAL_EDIT_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getHeaderData", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);

						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message = JsonUtils.getString(data, "message", "");
							Global.headPic = JsonUtils.getString(data, "u_avatar", "");
							showToast(message);
							SharedUtils.putString(context, "headPic",
									Global.headPic);
							Intent intent = new Intent();
							intent.setAction(MainActivity.ACTION_EDIT_INFORMATION);
							context.sendBroadcast(intent);
							finish();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	/**
	 * 头像点击事件
	 */
	private void img_head_perfection_click() {
		showHeadDialog((Activity) context);
	}

	private void showHeadDialog(Activity activity) {
		initHeadDialogView();
		if (null != dialogHead && dialogHead.isShowing()) {
			return;
		}
		if (null != dialogHead) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialogHead.getWindow();
			// 设置显示动画
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = ((Activity) context).getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
			// 设置显示位置
			dialogHead.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialogHead.setCanceledOnTouchOutside(true);
			dialogHead.show();
		}
	}

	private void initHeadDialogView() {
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_img_choice, null);
		LinearLayout tvFriends = (LinearLayout) view
				.findViewById(R.id.ll_album);
		tvFriends.setOnClickListener(this);
		LinearLayout tvFriendsCircle = (LinearLayout) view
				.findViewById(R.id.ll_camera);
		tvFriendsCircle.setOnClickListener(this);
		Button btnCancle = (Button) view.findViewById(R.id.btn_cancel);
		btnCancle.setOnClickListener(this);
		dialogHead = new Dialog(context, R.style.dialogWindowStyle);
		dialogHead.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogHead.setContentView(view, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

	/**
	 * 选择图片裁剪
	 */
	private void startImagePick() {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent();
			intent.setAction(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(Intent.createChooser(intent, "选择图片"),
					ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
		} else {
			intent = new Intent(Intent.ACTION_PICK,
					Images.Media.EXTERNAL_CONTENT_URI);
			intent.setType("image/*");
			startActivityForResult(Intent.createChooser(intent, "选择图片"),
					ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
		}
	}

	/**
	 * 相机拍照
	 */
	private void startActionCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
		startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	// 拍照保存的绝对路径
	private Uri getCameraTempFile() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			showToast("无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		// 照片命名
		String cropFileName = "osc_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		this.origUri = this.cropUri;
		return this.cropUri;
	}

	/**
	 * 拍照后裁剪
	 * 
	 * @param data
	 *            原始图片
	 */
	private void startActionCrop(Uri data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra("output", this.getUploadTempFile(data));
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		intent.putExtra("scale", true);// 去黑边
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边
		startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
	}

	// 裁剪头像的绝对路径
	private Uri getUploadTempFile(Uri uri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			showToast("无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);
		// 如果是标准Uri
		if (StringUtils.isEmpty(thePath)) {
			thePath = ImageUtils.getAbsoluteImagePath(this, uri);
		}
		String ext = FileUtils.getFileFormat(thePath);
		ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
		// 照片命名
		String cropFileName = "osc_crop_" + timeStamp + "." + ext;
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		return this.cropUri;
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
			startActionCrop(origUri);// 拍照后裁剪
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
			startActionCrop(data.getData());// 选图后裁剪
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
			showProgress();
			uploadNewPhoto();// 上传头像
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			this.finish();
			break;
		case R.id.tv_right:
			getHeaderData();
			break;
		case R.id.iv_header:
			img_head_perfection_click();
			break;
		case R.id.ll_album:
			if (null != dialogHead) {
				dialogHead.dismiss();
				startImagePick();
			}
			break;
		case R.id.ll_camera:
			if (null != dialogHead) {
				dialogHead.dismiss();
				startActionCamera();
			}
			break;
		case R.id.btn_cancel:
			if (null != dialogHead) {
				dialogHead.dismiss();
			}
			break;
		default:
			break;
		}
	}

}
